package com.juyu.miliao.scheduler.service;

import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.common.constant.BeansType;
import com.juyu.miliao.common.constant.CallTimeRankingListKey;
import com.juyu.miliao.common.constant.DiamondRankingListKey;
import com.juyu.miliao.common.constant.SpendSystemMessage;
import com.juyu.miliao.common.domain.BillDetailBeans;
import com.juyu.miliao.common.util.DateUtil;
import com.juyu.miliao.common.util.GameRankingListUtil;
import com.juyu.miliao.common.util.MessageSystemUtil;
import com.juyu.miliao.scheduler.dao.mysql.BillDetailBeansDao;
import com.juyu.miliao.scheduler.dao.mysql.GameAllRankingListDao;
import com.juyu.miliao.scheduler.dao.mysql.GameAllRankingListLogDao;
import com.juyu.miliao.scheduler.dao.mysql.UserWalletDao;
import com.juyu.miliao.scheduler.domin.GameAllRankingList;
import com.juyu.miliao.scheduler.domin.GameAllRankingListLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 *  排行榜 每天发放奖励
 * @Auther: 卜加超
 * @Date: 2019/8/20 20:47
 * @Description:
 */
@Component
public class GameRewardsService {
    private final Logger logger = LoggerFactory.getLogger(GameRewardsService.class);

    @Resource
    private GameAllRankingListDao gameAllRankingListDao;
    @Resource
    private GameAllRankingListLogDao gameAllRankingListLogDao;
    @Resource
    private UserWalletDao userWalletDao;
    @Resource
    private BillDetailBeansDao billDetailBeansDao;


    //每日排行榜 每天凌晨10分 发放昨日奖励(0 10 0 * * ?)
    @Scheduled(cron = "0 10 0 * * ?")
    @Transactional
    public void sendGameRewardsByDay(){
        logger.info("游戏排行日榜发放奖励定时任务开始....");
         List<GameAllRankingList> gameAllRankingDayList = gameAllRankingListDao.selectGameListByDay(LocalDate.now().minusDays(1));
         for(int i = 0;i<gameAllRankingDayList.size();i++){
             if(gameAllRankingDayList.get(i).getIsRobot()!=1){
                 int flag=userWalletDao.addUserSendBeans(gameAllRankingDayList.get(i).getUserId(), GameRankingListUtil.getGuoRewardMapByDay().get(i));
                 if(flag>0){
                     GameAllRankingListLog gameAllRankingListLog = new GameAllRankingListLog();
                     gameAllRankingListLog.setUserId(gameAllRankingDayList.get(i).getUserId());
                     gameAllRankingListLog.setProfit(gameAllRankingDayList.get(i).getReturnBean());
                     gameAllRankingListLog.setSort((i+1)+"");
                     gameAllRankingListLog.setRewardsBeans(GameRankingListUtil.getGameRankingRewardListByDay().get(i));
                     gameAllRankingListLog.setRewardsType(1);
                     gameAllRankingListLog.setRankingDate(gameAllRankingDayList.get(i).getCreateDate());
                     int j = gameAllRankingListLogDao.saveGameAllRankingListLog(gameAllRankingListLog);
                     if(j>0){
                         BillDetailBeans billDetailBeans = new BillDetailBeans();
                         billDetailBeans.setBeansType(BeansType.GAME_PROFIT_DAY_REWARDS__GIVE_BEANS.getCode());
                         billDetailBeans.setBeans(GameRankingListUtil.getGuoRewardMapByDay().get(i));
                         billDetailBeans.setRatio(0);
                         billDetailBeans.setUserId(gameAllRankingDayList.get(i).getUserId());
                         billDetailBeans.setCreateDate(LocalDate.now(ZoneOffset.of("+8")));
                         billDetailBeans.setCreateTime(LocalDateTime.now(ZoneOffset.of("+8")));
                         billDetailBeansDao.insert(billDetailBeans);

                         //发送系统消息 恭喜您，昨天盈利排行榜排名第"+(i+1)+"名，继续加油哦！
                         String message = SpendSystemMessage.PROFIT_RANKING_DAY_SEND_MESSAGE.getMessage(i+1);
                         MessageSystemUtil.sendCustomSystemMessage(gameAllRankingDayList.get(i).getUserId(),message);
                     }
                 }
             }
         }


        logger.info("游戏排行日榜发放奖励定时任务结束....");
    }

    //每周排行榜 每周一凌晨 半点 发放周榜奖励（0 30 0 ? * MON）
    @Scheduled(cron = "0 30 0 ? * MON")
    @Transactional
    public void sendGameRewardsByWeek(){
        logger.info("游戏排行周榜发放奖励定时任务开始....");
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        JSONObject weekByYearTime = DateUtil.getWeekByYearTime(LocalDate.now().minusWeeks(1));
        LocalDate startTime = LocalDate.parse(weekByYearTime.get("startTime").toString(),dateFormatter);
        LocalDate endTime = LocalDate.parse(weekByYearTime.get("endTime").toString(),dateFormatter);
        List<GameAllRankingList> gameAllRankingWeekList = gameAllRankingListDao.selectGameListByWeek(startTime,endTime);
        for(int i = 0;i<gameAllRankingWeekList.size();i++){
            List<GameAllRankingList> isRotoList =gameAllRankingListDao.selectUserIsRotoByWeek(
                    gameAllRankingWeekList.get(i).getUserId(),startTime,endTime);
            if(isRotoList.size()==0){
                logger.info("用户=[{}]不是机器人，发放奖励！",gameAllRankingWeekList.get(i).getUserId());
                int flag=userWalletDao.addUserSendBeans(gameAllRankingWeekList.get(i).getUserId(), GameRankingListUtil.getGuoRewardMapByWeek().get(i));
                if(flag>0){
                    GameAllRankingListLog gameAllRankingListLog = new GameAllRankingListLog();
                    gameAllRankingListLog.setUserId(gameAllRankingWeekList.get(i).getUserId());
                    gameAllRankingListLog.setProfit(gameAllRankingWeekList.get(i).getReturnBean());
                    gameAllRankingListLog.setSort((i+1)+"");
                    gameAllRankingListLog.setRewardsBeans(GameRankingListUtil.getGameRankingRewardListByWeek().get(i));
                    gameAllRankingListLog.setRewardsType(2);
                    gameAllRankingListLog.setRankingDate(gameAllRankingWeekList.get(i).getCreateDate());
                    int j = gameAllRankingListLogDao.saveGameAllRankingListLog(gameAllRankingListLog);
                    if(j>0){
                        BillDetailBeans billDetailBeans = new BillDetailBeans();
                        billDetailBeans.setBeansType(BeansType.GAME_PROFIT_WEEK_REWARDS__GIVE_BEANS.getCode());
                        billDetailBeans.setBeans(GameRankingListUtil.getGuoRewardMapByWeek().get(i));
                        billDetailBeans.setRatio(0);
                        billDetailBeans.setUserId(gameAllRankingWeekList.get(i).getUserId());
                        billDetailBeans.setCreateDate(LocalDate.now(ZoneOffset.of("+8")));
                        billDetailBeans.setCreateTime(LocalDateTime.now(ZoneOffset.of("+8")));
                        billDetailBeansDao.insert(billDetailBeans);

                        //发送系统消息
                        String message = SpendSystemMessage.PROFIT_RANKING_WEEK_URL_SEND_MESSAGE.getMessage(i+1);
                        MessageSystemUtil.sendCustomSystemMessage(gameAllRankingWeekList.get(i).getUserId(),message);
                    }
                }
            }
        }


        logger.info("游戏排行周榜发放奖励定时任务结束....");
    }
}
